import axios from "axios";
import qs from "qs";
import {devBaseURL, proBaseURl} from "./axiosConfig";

class HttpRequest {
    constructor() {
        this.baseURL = process.env.NODE_ENV === 'development' ? devBaseURL : proBaseURl;
        this.timeout = 5000;
    }

    getConfig() {
        const config = {
            baseURL: this.baseURL,
            timeout: this.timeout,
            headers: {}
        }
        return config
    }

    interceptor(instence) {

        instence.interceptors.request.use(function (config) {
            // Do something before request is sent
            console.log("触发request拦截！！！")
            return config;
        }, function (error) {
            // Do something with request error
            console.log("触发request失败拦截！！！")
            return Promise.reject(error);
        });

        instence.interceptors.response.use(function (response) {
            // Do something with response data
            console.log("触发response成功拦截！！！")
            return response;
        }, function (error) {
            // Do something with response error
            console.log("触发response失败拦截！！！")
            return Promise.reject(error);
        });
    }

    request() {
        const instence = new axios.create(this.getConfig());
        this.interceptor(instence);
        return instence;
    }
    //get方法
    axiosGet(url, params = {}) {
        return new Promise((resolve, reject) => {
            this.request().get(url, params)
                .then(function (response) {resolve(response);})
                .catch(function (error) {reject(error);})
        })
    }
    //对post请求参数使用qs组件转化格式
    postQS(params) {
        return qs.stringify(params);
    }
    //post方法
    axiosPost(url, params = {}) {
        return new Promise((resolve, reject)=>{
            this.request().post(url, this.postQS(params))
                .then(function(response){resolve(response)})
                .catch(function (error){reject(error)})
        })
    }
}

export {HttpRequest}